$(function(){
	/*
	 * 初始化活动时间
	 */
	$('.add-qin-time').datetimepicker({
		dayViewHeaderFormat: 'YYYY MMMM',
		locale: 'zh-cn',
		format: 'YYYY-MM-DD',
		keepInvalid: true,
	});	
	$('#begin_time,#end_time').data('DateTimePicker').useCurrent(false);
	$("#begin_time").on("dp.change", function (e) {
		$('#end_time').data("DateTimePicker").minDate(e.date);
	});
	$("#end_time").on("dp.change", function (e) {
		$('#begin_time').data("DateTimePicker").maxDate(e.date);
	});
	
	//###上传头像
	function handleUploadSuccess(obj) {
		var $this = this;
		var photoUrl = obj['data'];
		$this.siblings('.pic').css('background-image','url('+photoUrl+')');	
		$this.siblings('input:hidden').val(photoUrl);
		$this.parent().find('[download]').attr('href',photoUrl);
	}

	var uploader = new PicUploader({
		success: function(obj){
			handleUploadSuccess.call($curBtn,obj);
		}
	});

	$('.btn.upload').on('click',function(){
		uploader.start();
		$curBtn = $(this);
	});
	//上传头像###
	
	var searchUser = function(e){
		var $this = $(e);
		var seachWords = $this.val(); 
		var suggestTplStr = $('#searh-user-tpl').html();
		var $suggestContainer = $this.parent().next();
		var url = "";
		var _parse = false;
		if($this.attr('id')=="servicer_uname"){
			_url = "/cms/appUser/appUser/searchUserDing";
		}else{
			_url = "/base/api/searchUserByName";
		}
		cAjax({
			url: _url,
			data: {
				keywords: seachWords
			},
			success: function(obj) {
				var items = obj["data"];
				$("#recommended-ul,#servicer-ul").empty();
				$suggestContainer.empty();
				if(items.length == 0){
					$suggestContainer.append("没有结果...");
				}
				for(var index in items) {
					var data = items[index];
					var $itemEle = $(swig.render(suggestTplStr,{locals:{item:data}}));
					$suggestContainer.append($itemEle);		
				}
			}
		});
	}
	
	$('input.search-user').change(searchUser(this)).keyup(function(e){
		var ev = e || window.event;
		if ($(this).val()=='') {
			$(this).parent().next().empty();
		}else if(ev.keyCode == 13||ev.keyCode == 8){
			searchUser(this);
		}
	})
	
	$('div.input-group-btn').has("i.fa-search").click(function(){
		searchUser($(this).prev());
	});
	
	$("#servicer-ul,#recommended-ul").on("click","li",function(){
		var $this = $(this);
		if($this.parent().attr('id')=="servicer-ul"){
			$("input[name='servicer_uid']").val($this.data('uid'));
			$("#servicer_uname").val($this.data('uname'));
			$("input[name='servicer_mobile']").val($this.data('mobile'));
		}else{
			$("input[name='recommend_uid']").val($this.data('uid'));
			$("input[name='recommend_uname']").val($this.data('uname'));
			$("input[name='recommend_mobile']").val($this.data('mobile'));
		}
		$this.parent().empty();
	})
	
	$('input[name="recommend_uname"]').bind('input propertychange', function() {
		$('input[name="recommend_pkid"]').val('');
		$('input[name="recommend_uid"]').val('');
	});
	
	var flag = true;
	$('#main-info .save-btn').on('click',function(){
		var $btn = $(this).addClass('disabled');
		var $this = $(this);
		var country_code=$("#country_code").val();
		if(country_code==''){
			$btn.removeClass('disabled');
			alerting({msg:"国家区号不能为空！"});
			return false;
		}
		var mobile = $("input[name='mobile']").val();
		//手机号只校验是否是数字
		//var reg = /^0?1[0|3|4|5|7|8][0-9]\d{8}$/;
		var reg=/^[0-9]*$/;
		if (!reg.test(mobile)) {
			$btn.removeClass('disabled');
			alerting({msg:"手机号不合法！"});
			return false;
		}
		if($("input[name='head_url']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"头像不能为空！"});
			return false;
		}
		if($("input[name='uname']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"用户名不能为空！"});
			return false;
		}
		if($("input[name='mobile']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"登录账号不能为空！"});
			return false;
		}
		if($("input[name='com_name']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"认证公司不能为空！"});
			return false;
		}
		if($("input[name='position']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"职位不能为空！"});
			return false;
		}
		if($("input[name='begin_time']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"服务开始时间不能为空！"});
			return false;
		}
		if (!reg.test($("input[name='recommend_mobile']").val())&&$("input[name='recommend_mobile']").val()!='') {
			$btn.removeClass('disabled');
			alerting({msg:"推荐人手机号不合法！"});
			return false;
		}
		var formData = {};
		$('input[name]').each(function(m,n) {
			if($(n).val()!=''&&$(n).val()!="undefined"){
				formData[$(n).attr('name')] = $(n).val();
			}
		});
		formData['country_code']=country_code;
		formData['gender'] = $("input[name='gender']:checked").val();
		formData['user_type'] = $("input[name='user_type']:checked").val();
		if(formData['user_type']!=2){	//不是绿岛则不填写结束时间
			delete formData['end_time'];
		}else if(formData['user_type']==2&&$("input[name='end_time']").val()==''){
			$btn.removeClass('disabled');
			alerting({msg:"岛邻身份为绿岛时 服务结束时间不能为空！"});
			return false;
		}
		if(formData['user_type']!=1){	//非蓝岛必须有推荐人
			if($("input[name='recommend_uname']").val()==''){
				$btn.removeClass('disabled');
				alerting({msg:"推荐人不能为空！"});
				return false;
			}
			if($("input[name='recommend_mobile']").val()==''){
				$btn.removeClass('disabled');
				alerting({msg:"推荐人手机号不能为空！"});
				return false;
			}
		}
		console.log(formData);
		if($("input[name='user_id']").val()!=''){
			var _url =  '/cms/appUser/appUser/editUserQin';
		}else{
			var _url =  '/cms/appUser/appUser/addUserQin';
		}
		if(flag){
//			flag = false;
			cAjax({
				url:_url,
				data: formData,
				success: function() {
					$btn.removeClass('disabled');
					greeting({
						msg: '操作成功！',
						confirm:function(){
							window.location.href="/cms/appUser/appUser/list";
						}
					});
					//	window.location.reload();
				}
			});
		}
		$btn.removeClass('disabled');
	});
	
	
	
	var FillUserInfo = function(obj){
		$("input[name='user_id']").val(obj.user_id);
		$("input[name='uname']").val(obj.uname);
		$("input[name='company_id']").val(obj.company_id);
		$("input[name='com_name']").val(obj.com_name);
		$("input[name='position']").val(obj.position);
		$("#begin_time").data("DateTimePicker").date(new Date(obj.begin_time));
		$("#end_time").data("DateTimePicker").date(new Date(obj.end_time));
		$("input[name='base_rank']").val(obj.base_rank);
		$("input[name='head_url']").val(obj.head_url).next().css("background","url("+obj.head_url+")");
		if(obj.gender=="male"){
			$("input[name='gender'][value='male']").prop("checked",true);//男选中
		}else{
			$("input[name='gender'][value='female']").prop("checked",true);//女选中
		}
		
		if(obj.is_lifelong==1){
			$("input[name='user_type'][value='3']").prop("checked",true);//终身岛选中
		}else if(obj.zhisland_type==1){
			$("input[name='user_type'][value='1']").prop("checked",true);//绿岛选中
		}else if(obj.zhisland_type==2){
			$("input[name='user_type'][value='2']").prop("checked",true);//蓝岛选中
		}
		
		switch(obj.base_rank){
			case JSConst.get('USER_BASE_RANK_DING'):
				$("#br-labe").text("类型为：岛丁用户；");
				break;
			case JSConst.get('USER_BASE_RANK_PRE'):
				$("#br-labe").text("类型为：标准用户；");
				break;
			case JSConst.get('USER_BASE_RANK_INVITE'):
				$("#br-labe").text("类型为：优质用户；");
				break;
			case JSConst.get('USER_BASE_RANK_ISLAND'):
				$("#br-labe").text("类型为：岛邻用户；");
				break;
		}
	}
	
	var FillContactInfo = function(items){
		if(items.length != 0){
			for(var index in items) {
				if(items[index].contact_type=="contact_reterence"){
					$("input[name='recommend_pkid']").val(items[index].contact_id);
					$("input[name='recommend_uid']").val(items[index].referer_id);
					$("input[name='recommend_uname']").val(items[index].uname);
					$("input[name='recommend_mobile']").val(items[index].default_phone);
				}else if(items[index].contact_type=="contact_service"){
					cAjax({
						url: "/cms/appUser/appUser/searchUserByUid",
						data: {
							user_id: items[index].referer_id
						},
						success: function(obj) {
							console.log(obj["data"]);
							item = JSON.parse(obj["data"]);
							if(obj["data"]!=""&&obj["data"]!=null){
								$("input[name='servicer_uid']").val(item.user_id);
								$("#servicer_uname").val(item.uname);
							}
						}
					});
				}
			}
		}
	}
	
	var getContactInfo = function(user_id){
		cAjax({
			url: "/cms/appUser/appUser/getContactInfo",
			data: {
				user_id: user_id
			},
			success: function(obj) {
				console.log(obj["data"]);
				if(obj["data"]!=""&&obj["data"]!=null){
					FillContactInfo(obj["data"]);
				}
			}
		});
	}
	
	
	$("input[name='mobile']").blur(function(){
		var curr = $(this);
		var mobile = $(this).val();
		var country_code=$("#country_code").val();
		var reg = /^[0-9]*$/;
		if (!reg.test(mobile)) {
		      return false;
		}
		cAjax({
			url: "/cms/appUser/appUser/searchUserByMobile",
			data: {
				country_code:country_code,
				mobile: mobile
				
			},
			success: function(obj) {
				console.log(obj["data"]);
				if(obj["data"]!=""&&obj["data"]!=null){//手机号存在
					//询问是否填充下面表单
					var items = JSON.parse(obj["data"]);
					actionConfirm({
						msg: "手机号："+mobile+"的用户已存在，是否自动填充表单？",
						confirm: function(){
							//$("#exists_mobile").html(items.account);
							$("#account-exist-tip").show();
							FillUserInfo(items);
							getContactInfo(items.user_id);
						},
						cancle:function(){
							$(curr).val('');
							$("input[name='user_id']").val('');
							$("input[name='base_rank']").val('');
							$("#account-exist-tip").hide();
						}
					});
				}else{//不存在  新增
					$("input[name='user_id']").val('');
					$("#account-exist-tip").hide();
//					$("input[name!=mobile]:text").val('');
//					$("input[name='gender']").eq(0).prop("checked",true);
//					$("input[name='user_type']").eq(0).prop("checked",true);
//					$("input[name='head_url']").val('').next().css("background","");
				}
			}
		});
	})
	
	//页面联动
	$("input[name='user_type']").change(function(){
		if($(this).val()=="2"){
			$("#end-time-rapper").show();
		}else{
			$("#end-time-rapper").hide();
		}
	})
	$("#country_code_name").on("change",function(){
		$("input[name='country_code']").val($("#country_code_name").val());
	})
});
